package com.sdgakj.service.login;

import com.sdgakj.dto.AuthInfo;
import com.sdgakj.dto.weixinUserInfo;
import com.sdgakj.entity.Family;
import com.sdgakj.entity.Person;
import com.sdgakj.entity.ShtCity;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumUserType;
import com.sdgakj.repository.UserDao;
import com.sdgakj.rest.CommonRestController;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.utils.HttpClientUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by win10 on 2017/6/27.
 */
@Component
@Transactional
public class LoginByWechatService {
    private static Logger logger = LoggerFactory.getLogger(LoginByWechatService.class);
    private static final String APPID = "wx812c260c8e3bf9aa";
    private static final String APPSECRET = "86d9e7f8294b1a54b6ff73d6d4140d33";
    private static final String IMGSIZE = "96";
    private static final String IF_ERR = "{\"errcode\":";

    @Autowired
    private UserDao userDao;

    @Autowired
    private PersonService personService;
    //通过code获取权限以及登录
    public User  weixinLogin(String code) {
        AuthInfo authInfo = getAuthInfo(code);
        if (authInfo != null) {
            logger.info("成功获取用户授权信息");
            // 持久化用户信息
             return requestCustomerInfo(authInfo);
        }
        return null;
    }
    /*
    * 获取用户access_token
    * */
    private AuthInfo getAuthInfo(String code){
        logger.info("通过code获取access_token......");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("appid", APPID);
        param.put("secret", APPSECRET);
        param.put("code", code);
        param.put("grant_type", "authorization_code");
        String str = HttpClientUtil.doGet(url, param);
        if (str != null && str.contains(IF_ERR)) {
            logger.error("微信服务器返回错误信息:" + str);
            return null;
        }
        JSONObject json=JSONObject.fromObject(str);
        AuthInfo authInfo= (AuthInfo) JSONObject.toBean(json,AuthInfo.class);
        return authInfo;
    }
    //根据用户授权获取用户个人信息以及保存到数据库
    public User requestCustomerInfo(AuthInfo authInfo){
        User user=userDao.findUserByOpenid(authInfo.getOpenid());//authInfo.getOpenid());//稍后改接口
        //判断该微信用户是否已经存在
        if(user==null){
            //没存在 持久化到数据库  首先通过openid 获取用户信息
            weixinUserInfo weixinUserInfo=getweixinByOpenid(authInfo);
            if(weixinUserInfo!=null){
                user=saveUserByweixin(weixinUserInfo);
            }else {
                logger.error("读取用户信息失败！");
            }
        }
        return user;
    }

    /**
     * 通过access_token获取用户详细信息
     * */
    private weixinUserInfo getweixinByOpenid(AuthInfo authInfo) {
        String url = "https://api.weixin.qq.com/sns/userinfo";
        Map<String, String> map = new HashMap<String, String>();
        map.put("access_token", authInfo.getAccess_token());
        map.put("openid", authInfo.getOpenid());
        map.put("lang","zh_CN");
        String str=HttpClientUtil.doGet(url,map);
        if ( str != null &&str.contains(IF_ERR)) {
            logger.error("获取用户信息失败，错误信息：" + str);
            return null;
        }
        JSONObject json=JSONObject.fromObject(str);
        weixinUserInfo weixinUser=null;
        try {
            weixinUser= (weixinUserInfo) JSONObject.toBean(json,weixinUserInfo.class);
            return weixinUser;
        }catch (Exception e){
            logger.error("weixinUserInfo转换失败！");
        }
        return  weixinUser;
    }


    /**
     * 对微信用户的持久化操作
     * */
    private User saveUserByweixin(weixinUserInfo weixinUser){
       /* System.out.println("对微信用户进行持久化操作");
        System.out.println("对微信信息："+weixinUser);*/
        weixinUser.setHeadimgurl(convertHeadImg(weixinUser.getHeadimgurl()));
        Integer sex=Integer.parseInt(weixinUser.getSex());
        weixinUser.setSex(convertSex(sex).toString());
        // 转换微信用户昵称
        weixinUser.setNickname(convertNickName(weixinUser.getNickname()));
        //给user填充信息
        User user=new User();
        user.setLoginName(weixinUser.getNickname());
        user.setName(weixinUser.getNickname());
        user.setPassword("123456");//默认密码
        user.setIntegration(100);
        user.setDeltag(EnumIsDelete.NOTDELETE.getCode());
        user.setType(EnumUserType.CUSTOMOR.getCode());
        user.setOpenid(weixinUser.getOpenid());
        user.setSex(weixinUser.getSex());
        user.setStatus("0");
        //System.out.println("user:"+user);
        User u=userDao.save(user);
        //向person增加一名用户
        Person person=new Person();
        person.setCreatetime(new Date());
        person.setUpdatetime(new Date());
        person.setName(u.getLoginName());
        person.setAvatar(weixinUser.getHeadimgurl());
        if(u.getSex().equals("1")){
            person.setS("M");
        }else {
            person.setS("F");
        }
        person.setM(0L);
        person.setF(0L);
        person.setVir(0L);
        person.setUx(0L);
        Family family=new Family();
        family.setId(0L);
        person.setUser(u);
        //添加成功后返回的personid
        Long pid=personService.savePerson(person);
        //通过personid查询person信息
        person=personService.getPersonById(pid);
        u.setPerson(person);
        userDao.save(u);
        return u;
    }

    // 如果是微信用户头像就将图片大小转换成96*96
    private String convertHeadImg(String headimgurl) {
        if (headimgurl.startsWith("http://wx")) {
            headimgurl = headimgurl.substring(0, headimgurl.length() - 1) + IMGSIZE;
        }
        return headimgurl;
    }
    // 转换性别数据库中0代表女 微信返回数据2代表女，以本地数据库为准
    private Integer convertSex(Integer sex) {
        if (sex != null && sex == 2) {
            sex = 0;
        }
        return sex;
    }
    // 由于用户昵称可能存在emoji表情所以对用户昵称进行解码后转换处理
    private String convertNickName(String nickName) {
        try {
            nickName = URLDecoder.decode(nickName, "utf-8").replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]",
                    "");
        } catch (UnsupportedEncodingException e) {
            logger.error("微信登录获取用户昵称时产生异常");
            e.printStackTrace();
        }
        return nickName;
    }
}
